/**
 * Wihidum - Efficient Broker Hierarchy for Publish Subscribe Middleware
 *
 * License      :   Apache License 2.0
 * Home Page    :   http://code.google.com/p/wihidum/
 * Mailing List :   wihidum@googlegroups.com
 */

package lk.mrt.cse.wihidum.storage;

import org.apache.log4j.Logger;

import java.util.*;

public class BrokerSubscriptionMap
{
    private static final Logger logger=Logger.getLogger(BrokerSubscriptionMap.class);
    private static Map<String ,BrokerSubscription> brokerSubscriptionMap=new HashMap<String,BrokerSubscription>();
    public static void saveSubscriber(String uuid,BrokerSubscription brokerSubscription)
    {
        brokerSubscriptionMap.put(uuid,brokerSubscription);
    }
    public static ArrayList<BrokerSubscription> getBrokerSubscribersFilteredByTopic(String topic)
    {
       // ArrayList<BrokerSubscription> filteredBrokerSubscribers=new ArrayList<BrokerSubscription>();
        ArrayList<BrokerSubscription> filteredBrokerSubscribers=new ArrayList<BrokerSubscription>();
        for(Map.Entry<String,BrokerSubscription> entry:brokerSubscriptionMap.entrySet())
        {
            String filterTopic=entry.getValue().getTopic();
            String fromBrokerAddress=entry.getValue().getFromBrokerAddress();

            if( fromBrokerAddress != null && !fromBrokerAddress.isEmpty() && topic.equals(filterTopic))
            {
                filteredBrokerSubscribers.add(entry.getValue());
            }
        }
      /*  if(filteredBrokerSubscribers.isEmpty())
        {
            logger.info("No registered BrokerSubscribers Found for topic: "+topic);
        }
        else
        {
            logger.info(filteredBrokerSubscribers.size()+" number of broker subscribers found.");
        }  */

        return filteredBrokerSubscribers;
    }
    public static boolean isSubscribedTo(NeighbourBroker neighbourBroker,String topic)
    {
        boolean isSubscribed=false;
        for(Map.Entry<String,BrokerSubscription> entry: brokerSubscriptionMap.entrySet())
        {
               String brokerID=entry.getValue().getToBrokerID();
               String filterTopic=entry.getValue().getTopic();
            if(brokerID != null && brokerID.equals(neighbourBroker.getBrokerID()) && filterTopic.equals(topic))
            {
                 isSubscribed=true;
                 break;
            }

        }
        return isSubscribed;

    }
}
